﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace Doudizhu
{
    public class TimerController : MonoBehaviour
    {
        public Sprite[] numSprites;

        private Image _num1_img;
        private Image _num2_img;

        private int _timerIndex = 0;

        private void Awake()
        {
            _num1_img = transform.Find("num1_img").GetComponent<Image>();
            _num2_img = transform.Find("num2_img").GetComponent<Image>();
        }

        public void StartTimer(int time, Action action)
        {
            StartCoroutine(startTimerAsync(_timerIndex++, time, action));
        }

        public void StopTimer()
        {
            _timerIndex++;
        }

        private IEnumerator startTimerAsync(int index, int time, Action action)
        {
            while (time >= 0)
            {
                if (index != _timerIndex) break;
                setTime(time--);
                yield return new WaitForSeconds(1);
            }
            if (index == _timerIndex)
                action?.Invoke();
        }

        private void setTime(int time)
        {
            int num1 = time / 10;
            int num2 = time % 10;

            if (num1 > 0)
            {
                _num1_img.gameObject.SetActive(true);
                _num1_img.sprite = numSprites[num1];
            }
            else
            {
                _num1_img.gameObject.SetActive(false);
                _num1_img.sprite = numSprites[0];
            }

            _num2_img.sprite = numSprites[num2];
        }
    }
}
